package com.zy.fee.roadpark.activity.np;

import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.printer.sdk.Barcode;
import com.printer.sdk.PrinterConstants;
import com.spd.print.jx.impl.PrintImpl;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.adapter.EscapeListAdapter;
import com.zy.fee.roadpark.app.AppApplication;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Escape;
import com.zy.fee.roadpark.model.M_EscapeItem;
import com.zy.fee.roadpark.model.apimodel.APIM_EscapeList;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.ColorUtil;
import com.zygk.library.util.Convert;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.RxTextTool;
import com.zygk.library.view.SmoothListView.SmoothListView;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Wikison on 2019/4/3.
 * 补缴单据列表
 */
public class NpPayBackListActivity extends BaseActivity
    implements SmoothListView.ISmoothListViewListener {
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.tv_hint) TextView tvHint;
  @BindView(R.id.smoothListView) SmoothListView mSmoothListView;
  @BindView(R.id.tv_lotName) TextView tvLotName;
  @BindView(R.id.iv_search) ImageView ivSearch;
  @BindView(R.id.tv_money) TextView tvMoney;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;

  private EscapeListAdapter escapeListAdapter;
  private List<M_Escape> mEscapes = new ArrayList<>();
  private int page = 0;
  private String plateNumber = "";

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_np_pay_back_list);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    registerReceiver(new String[] { Constants.BROADCAST_REFRESH_OVERPAY_BILL_LIST });

    escapeListAdapter = new EscapeListAdapter(mContext, mEscapes);
    mSmoothListView.setAdapter(escapeListAdapter);

    mSmoothListView.setSmoothListViewListener(this);
    mSmoothListView.setRefreshEnable(true);
    mSmoothListView.setLoadMoreEnable(false);

    getEscapeList(false);
  }

  private void initView() {
    lhTvTitle.setText("补缴单据列表");
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 2 && position <= 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {

      }

      @Override public void onInputFinish(String psw) {
      }
    });

    ivSearch.setOnClickListener(v -> {
      plateNumber = gpvPlateNumber.getPassWord();
      viewKeyboard.setVisibility(View.GONE);
      getEscapeList(false);
    });

    gpvPlateNumber.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      }
    });

    escapeListAdapter.setOnPrintClickListener(mCarNumber -> {
      CommonDialog.showYesOrNoDialog(mContext, "是否打印补缴汇总单", "是", "否", () -> {
      }, () -> {
        printMainTicket(mCarNumber);
      });
    });
  }

  private void getEscapeList(boolean isLoadMore) {
    NpNodeRecordLogic.npnode_getEscapeList(mContext,
        preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID), plateNumber,
        isLoadMore ? ++page : (page = 1), Constants.ROWS, new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_EscapeList result = (APIM_EscapeList) obj;
            tvLotName.setText(result.getLotName());
            RxTextTool.getBuilder("", mContext)
                .append("欠收总额：")
                .setBold()
                .append(Convert.getMoneyString(result.getTotalMoney()))
                .setBold()
                .setForegroundColor(ColorUtil.getColor(mContext, R.color.theme_red))
                .append(" 元")
                .setBold()
                .into(tvMoney);
            fillAdapter(result.getEscapeList(), result.getMaxpage(), isLoadMore);
          }

          @Override public void onFailed() {
            dismissPd();
          }

          @Override public void onFinish() {
            dismissPd();
            mSmoothListView.stopRefresh();
            mSmoothListView.stopLoadMore();
          }
        });
  }

  // 填充数据
  private void fillAdapter(List<M_Escape> list, int maxPage, boolean isLoadMore) {
    if (list == null || list.size() == 0) {
      tvHint.setVisibility(View.VISIBLE);
      mSmoothListView.setVisibility(View.GONE);
      mSmoothListView.setLoadMoreEnable(false);
    } else {
      tvHint.setVisibility(View.GONE);
      mSmoothListView.setVisibility(View.VISIBLE);
      mSmoothListView.setLoadMoreEnable(page < maxPage);
      escapeListAdapter.setData(list, isLoadMore);
    }
  }

  private void printMainTicket(M_Escape mCarNumber) {
    try {
      PrintImpl mPrinter = AppApplication.getPrinterImpl();
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      StringBuilder sb = new StringBuilder();
      sb.append("欠费追缴告知单");
      sb.append("\n");
      sb.append("（汇总）");
      mPrinter.printText(sb.toString());

      mPrinter.setPrinter(1, 1);
      mPrinter.setPrinter(2, 0);

      sb = new StringBuilder();
      sb.append("车牌号:   " + mCarNumber.getCarNumber());
      sb.append("\n");
      sb.append(
          "追缴路段: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_NAME));
      sb.append("\n");
      sb.append("欠费笔数:   " + mCarNumber.getEscapes().size());
      sb.append("\n");
      double money = 0;
      for (M_EscapeItem nodeRecord : mCarNumber.getEscapes()) {
        money += nodeRecord.getMoney();
      }
      sb.append(
          "欠费金额:   " + Convert.getMoneyString3(money));
      sb.append("\n");
      sb.append("追缴时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      sb.append("收款单位:   " + "尚盈车联");
      sb.append("\n");
      sb.append("交费查询电话:   " + AppApplication.instance().parkTelephone);
      sb.append("\n");
      sb.append("1.免责声明：请遵守《交通法》第56条之规定，一车一位，线内顺向停放。停车期间车辆发生碰擦及车内财物的丢失需要自行承担。");
      sb.append("\n");
      sb.append("2.温馨提示：停车照片已上传取证，请及时缴费，欠费行为将被计入个人诚信系统，将对您后期的停车权益造成影响。");
      sb.append("\n");
      sb.append("\n");

      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);
      mPrinter.printText(sb.toString());

      String url =
          "https://www.ychel.com/pay?state=carnum";

      Barcode barcode = new Barcode(PrinterConstants.BarcodeType.QRCODE, 2, 3, 6, url);
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.printBarCode(barcode);

      sb = new StringBuilder();
      sb.append("微信或支付宝扫码自助缴费");
      sb.append("\n");
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.printText(sb.toString());

      sb = new StringBuilder();
      sb.append("\n");
      sb.append("\n");
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      mPrinter.printText(sb.toString());
      mPrinter.setPrinter(1, 2);

      Thread.sleep(3000);

      CommonDialog.showYesOrNoDialog(mContext, "是否继续打印追缴明细", "是", "否", () -> {
      }, () -> {
        //打印明细
        printListTicket(mCarNumber);
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void printListTicket(M_Escape mCarNumber) {
    try {
      PrintImpl mPrinter = AppApplication.getPrinterImpl();
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      StringBuilder sb = new StringBuilder();
      sb.append("欠费追缴告知单");
      sb.append("\n");
      sb.append("（明细）");
      mPrinter.printText(sb.toString());

      mPrinter.setPrinter(1, 1);

      mPrinter.setPrinter(2, 0);

      sb = new StringBuilder();
      sb.append("车牌号:   " + mCarNumber.getCarNumber());
      sb.append("\n");
      sb.append(
          "追缴路段: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_NAME));
      sb.append("\n");
      sb.append("打印时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      // 字号使用默认
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);
      mPrinter.printText(sb.toString());

      for (M_EscapeItem nodeRecord : mCarNumber.getEscapes()) {
        sb = new StringBuilder();
        sb.append("-----------------------------");
        sb.append("\n");
        sb.append(nodeRecord.getLotName());
        sb.append("\n");
        sb.append("驶入时间:   " + nodeRecord.getStartTime());
        sb.append("\n");
        sb.append("停车时长:   " + DateTimeUtil.parkTimeInfo(nodeRecord.getSecond() / 60));
        sb.append("\n");
        sb.append("追缴金额:   " + Convert.getMoneyString3(nodeRecord.getMoney()));
        sb.append("\n");

        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(2, 0);
        mPrinter.printText(sb.toString());
      }
      sb = new StringBuilder();
      sb.append("\n");
      sb.append("\n");
      sb.append("\n");

      // 字号使用默认
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);
      mPrinter.printText(sb.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_REFRESH_OVERPAY_BILL_LIST.equals(intent.getAction())) {
      getEscapeList(false);
    }
  }

  @OnClick({
      R.id.ll_back
  }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
    }
  }

  @Override public void onRefresh() {
    getEscapeList(false);
  }

  @Override public void onLoadMore() {
    getEscapeList(true);
  }
}
